package com.onepice.mlp.core.serviceImpl;

import com.onepice.mlp.core.service.ParamService;
import com.onepice.mlp.data.dao.ParamDao;
import com.onepice.mlp.data.entity.Param;
import com.onepice.mlp.utils.commom.ConvUtil;
import com.onepice.mlp.utils.commom.PageUtil;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author FireWang
 * @date 2022/07/13 01:02:44
 */
@Service
@AllArgsConstructor
@Transactional
public class ParamServiceImpl implements ParamService {
    private ParamDao paramDao;

    @Override
    public List<Param> getAll() {
        return paramDao.findAll();
    }

    @Override
    public Param getById(Integer id) {
        Optional<Param> param = paramDao.findById(id);
        return param.get();
    }

    @Override
    public void insert(Param param) {
        paramDao.save(param);
    }

    @Override
    public void update(Param param) {
        paramDao.save(param);
    }

    @Override
    public void deleteById(Integer id) {
        paramDao.deleteById(id);
    }

    @Override
    public Page<Param> getParamForPage(PageUtil page) {
        //查询规格定义
        Specification<Param> specification = new Specification<Param>() {

            /**
             * 构造断言
             * @param root 实体对象引用
             * @param query 规则查询对象
             * @param cb 规则构建对象
             * @return 断言
             */
            @Override
            public Predicate toPredicate(Root<Param> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                String name = ConvUtil.convToString(page.getParamMap().get("name"));
                if(!"".equals(name)){
                    predicates.add(cb.like(root.get("name").as(String.class),"%" + name +"%"));
                }
                return cb.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        //分页查询
        return paramDao.findAll(specification, page.getPageable());
    }
}
